<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    #outer{
        width: 300px;
        height: 300px;
        background-color: hotpink;
        color: yellow;
        display: flex;
        flex-wrap: nowrap;
        flex-direction: column;
        justify-content: space-between;
        margin-top: 50px;
    }
  </style>
</head>
<body>
  <h1>基础的get请求</h1>
  <form action="" id="aForm">

    <input placeholder="请输入id" id="ipt" type="text">
    <button id="btn">点击查询数据</button>

  </form>

  <div id="outer">
    <p>用户名:<span class="userName"></span></p>
    <p>性别:<span class="userSex"></span></p>
    <p>年龄:<span class="userAge"></span></p>
  </div>
  <script>
    const btn = document.querySelector('button')
    const aForm = document.querySelector('form')
    const ipt = document.querySelector('#ipt')
    const outer = document.querySelector('#outer')
    const userName = document.querySelector('.userName')
    const userSex = document.querySelector('.userSex')
    const userAge = document.querySelector('.userAge')
    //建立ajax
    aForm.onsubmit = function () {
      //将input表单中输入的值传给查询字符串userId
      const userId = ipt.value

      const xhr = new XMLHttpRequest()
      //添加时间戳
      xhr.open('GET',`/user?userId=${userId}&${Date.now()}`,true)
      xhr.send()
      xhr.onreadystatechange = function () {
        if (xhr.readyState===4 && xhr.status>=200&&xhr.status<=299){
          console.log('userId',userId)
          console.log(xhr.responseText)
          //获取的数据为JSON格式 需要进行转换
          let userList = JSON.parse(xhr.responseText)
          // console.log(userList)
          userName.innerHTML = userList.data.userName
          userSex.innerHTML = userList.data.userSex
          userAge.innerHTML = userList.data.userAge
        }
      }

      //防止默认事件
      return false
    }
  </script>
</body>
</html>